import React, { Component } from 'react';
import { Card, Statistic, Row, Col } from 'antd';
//按需导入
// import echarts from 'echarts/lib/echarts';
//导入折现图
import 'echarts/lib/chart/line';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/markPoint';
import ReactEcharts from 'echarts-for-react';
// import axios from '../../axios';
// import { getCookie } from './../../utils/common';
import Utils from './../../utils/utils';
import "./index.less";

let systemInfoData = {};
let currentSystemInfoData = {};
let xData = [];
let cpuData = [];//cpu数据
let ramData = [];//内存数据

class Line extends Component {
	
	
	componentDidMount(){
		this.hasNewSocket();
	}
	
	hasNewSocket = () => {
		let ws = null;
		// let cookie = getCookie("jqmkj_ss");
		ws = new WebSocket("ws://192.168.188.209:9501", "gujqnhl4mwulp57tjr2edybs1oeatghn");	
		//重试创建socket连接
		try {
			ws.connection();
		} catch (e) {
			//捕获异常
		}
		//连接
		ws.onopen = function(){
			// console.log("连接成功");
			let send_data = {
				"class": "monitor",
				"action": "getCurrentSystemInfo",
				"data": {}
			}
			let send_data2 = {
				"class": "monitor",
				"action": "getSystemInfo",
				"data": {}
			}
			if(ws.readyState === 1){
				ws.send(JSON.stringify(send_data));
				ws.send(JSON.stringify(send_data2));
			}
		}
		
		// 关闭 websocket
		ws.onclose = function(){ 
		  // console.log("连接已关闭"); 
		}		
		
		//接收数据
		var _this = this;
		ws.onmessage = function(evt){
			let data = JSON.parse(evt.data);
			if(data && data.action && data.data.result){
				if(data.action === "getSystemInfo"){
					systemInfoData = data.data.result;
				}else{
					currentSystemInfoData = data.data.result;
				}
			}
			if(systemInfoData && systemInfoData.length>0){
				xData = systemInfoData.map(item=>{
					return item[1]
				})
				cpuData = systemInfoData.map(item=>{
					return item[2]
				})
				ramData = systemInfoData.map(item=>{
					return item[3]
				})
			}
			
			//使页面重新渲染
			_this.setState({xx:1});
		}
	}
	
	getOption = () => {
		let option = {
			xAxis:{
				data:xData
			},
			yAxis:{
				name: "%",
				type: 'value'
			},
			toolbox: {               //右上角工具栏
				feature: {
					restore: {iconStyle: {borderColor: '#9da4b4'}},                       //还原
					magicType: { type: ["bar","line"],iconStyle: {borderColor: '#9da4b4'}},//切换图表类型
					saveAsImage: {iconStyle: {borderColor: '#9da4b4'}}                    //保存为图片
				},
				top: "4%",
				right: "5%",         //使整个toolbox向左移5%的宽度
				textStyle: {
					color: '#9da4b4' //图例文本颜色
				}
			},
			tooltip: {               //鼠标移入，提示信息
				trigger: 'axis',     //坐标轴触发，使提示框显示
				axisPointer: {
					type: 'cross',   //十字准星触发，y轴辅助线两端有显示具体y轴数值
					label: {
						backgroundColor: '#177af9',//辅助线两端显示具体y轴数值的背景色
						shadowColor: '#283548'
					}
				},
				formatter: function(params,ticket,callback){
					var str = params[0].axisValue +"<br/>"
							+ params[0].marker + params[0].seriesName +": "+ params[0].value.toFixed(2) + "%";
					return str
				}
			},
			dataZoom: [{             //底部滑块
				start: 0,            //起始值位置百分比
				end: 100,			 //终点值位置百分比
				height: 18,          //滑块高度
				textStyle: {color: "#9da4b4"},     //鼠标移到把柄上显示文字的颜色
				borderColor: "rgba(255,255,255,.2)"//滑块边框颜色
			}],
			series: [
				{
					name: 'cpu负载',
					type: 'line',
					color: "#189aff",
					lineStyle: {
						color: "#189aff"//线段颜色
					},
					data: cpuData
				}
			]
		}
		return option;
	}
	getOption2 = () => {
		let option = {
			xAxis:{
				data:xData
			},
			yAxis:{
				name: "%",
				type: 'value'
			},
			toolbox: {               //右上角工具栏
				feature: {
					restore: {iconStyle: {borderColor: '#9da4b4'}},                       //还原
					magicType: { type: ["bar","line"],iconStyle: {borderColor: '#9da4b4'}},//切换图表类型
					saveAsImage: {iconStyle: {borderColor: '#9da4b4'}}                    //保存为图片
				},
				top: "4%",
				right: "5%",         //使整个toolbox向左移5%的宽度
				textStyle: {
					color: '#9da4b4' //图例文本颜色
				}
			},
			tooltip: {               //鼠标移入，提示信息
				trigger: 'axis',     //坐标轴触发，使提示框显示
				axisPointer: {
					type: 'cross',   //十字准星触发，y轴辅助线两端有显示具体y轴数值
					label: {
						backgroundColor: '#177af9',//辅助线两端显示具体y轴数值的背景色
						shadowColor: '#283548'
					},
				},
				formatter: function(params,ticket,callback){
					var str = params[0].axisValue +"<br/>"
							+ params[0].marker + params[0].seriesName +": "+ params[0].value.toFixed(2) + "%";
					return str
				}
			},
			dataZoom: [{             //底部滑块
				start: 0,            //起始值位置百分比
				end: 100,			 //终点值位置百分比
				height: 18,          //滑块高度
				textStyle: {color: "#9da4b4"},     //鼠标移到把柄上显示文字的颜色
				borderColor: "rgba(255,255,255,.2)"//滑块边框颜色
			}],
			series: [
				{
					name: '内存使用',
					type: 'line',
					color: "#189aff",
					lineStyle: {
						color: "#189aff"//线段颜色
					},
					data: ramData
				},
			]
		}
		return option;
	}
	
	render(){
		return (
			<div style={{width: '100%', padding: '20px'}}>
				<Row gutter={16}>
					<Col md={{ span: 24}} lg={{ span: 8}} style={{marginBottom: 20}}>
						<Card title="cpu状态" className="monitor-card card-style1">
							<div className="monitor-card-flex">
								<Statistic title="CPU iowait" value={currentSystemInfoData.iowait} suffix=" %" />
								<Statistic title="CPU 负载" value={currentSystemInfoData.cpuloadfive} suffix=" %" />
								<Statistic title="CPU 使用" value={currentSystemInfoData.cpuuser} suffix=" %" />
							</div>
						</Card>
					</Col>
					<Col md={{ span: 24}} lg={{ span: 8}} style={{marginBottom: 20}}>
						<Card title="内存使用" className="monitor-card card-style2">
							<div className="monitor-card-flex">
								<Statistic title="总内存" value={Utils.merticKB(currentSystemInfoData.memtotal)} />
								<Statistic title="已使用" value={Utils.merticKB(currentSystemInfoData.memused)} />
							</div>
						</Card>
					</Col>
					<Col md={{ span: 24}} lg={{ span: 8}} style={{marginBottom: 20}}>
						<Card title="存储空间" className="monitor-card card-style3">
							<div className="monitor-card-flex">
								<Statistic title="总空间" value={Utils.merticKB(currentSystemInfoData.rootspace)} />
								<Statistic title="已使用空间" value={Utils.merticKB(currentSystemInfoData.rootused)} />
								<Statistic title="剩余空间" value={Utils.merticKB(currentSystemInfoData.rootunused)} />
							</div>
						</Card>
					</Col>
				</Row>
				<Row gutter={16}>
					<Col md={{ span: 24}} lg={{ span: 12}} style={{marginBottom: 20}}>
						<Card title="cpu负载">
							<ReactEcharts option={this.getOption()} theme="Imooc" style={{height: 400}} />
						</Card>
					</Col>
					<Col md={{ span: 24}} lg={{ span: 12}} style={{marginBottom: 20}}>
						<Card title="内存使用">
							<ReactEcharts option={this.getOption2()} theme="Imooc" style={{height: 400}} />
						</Card>
					</Col>
				</Row>
			</div>
		)
	}
}

export default Line;